from PyQt5.QtCore import Qt
from pathlib import Path
from pyecharts import options as opts
from pyecharts.charts import Line
from PyQt5.QtWidgets import QFileDialog
from qfluentwidgets import FluentWindow, InfoBar, InfoBarPosition, ComboBox
from qfluentwidgets import Dialog


class Tool(FluentWindow):

    def __init__(self):
        super(Tool, self).__init__()
        self.path = None
        self.suffix = None

    def prompt(self, widget_btn, title, content):
        """提示信号"""
        widget_btn.clicked.connect(
            lambda: self.show_message(title=title, content=content))

    def show_message(self, title, content):
        """提示弹窗"""
        d = Dialog(title, content, self)
        if d.exec():
            pass
        else:
            pass

    def get_widget_text(self, widget):
        """获取组件text"""
        widget_list = []
        for value in widget.children():
            if isinstance(value, ComboBox):
                widget_list.append(value.text())
        return widget_list

    def get_text(self, ui_text):
        """获取文本"""
        return ui_text.text()

    def handle_path(self, ui_line):
        """处理路径"""
        self.get_file_path(ui_line)  # 写入其他路径

    def get_suffix(self, ui_line):
        """判断后缀"""
        self.path = ui_line.text()  # 获取路径
        self.suffix = Path(self.path).suffix

    def csv_file_path(self, widget, ui_line):
        """写入csv文件路径"""
        self.get_file_path(widget)
        self.handle_csv_path(ui_line)

    def excel_file_path(self, widget, widget_line):
        """写入excel文件路径"""
        self.get_file_path(widget)
        self.handle_excel_path(widget_line)

    def handle_excel_path(self, widget_line):
        """处理excel"""
        self.path = widget_line.text()

    def handle_csv_path(self, widget_line):
        """处理获取数据"""
        self.path = widget_line.text()

    def get_file_path(self, widget_line_name):
        """保存路径+名称"""
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(None, "选择文件", "",
                                                   "All Files (*);;Text Files (*.txt);;Image Files (*.log)",
                                                   options=options)
        if file_name:
            widget_line_name.setText(file_name)

    @staticmethod
    def show_success(self):
        """在主线程中执行 InfoBar.success"""
        InfoBar.success(
            title='√操作成功',
            content="数据解析完成。",
            orient=Qt.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            duration=2000,
            parent=self
        )

    @staticmethod
    def show_warn(self):
        InfoBar.warning(
            title='×缺少参数',
            content="请检查参数完整性。",
            orient=Qt.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            duration=2000,
            parent=self
        )

    @staticmethod
    def show_error(self, title, content):
        InfoBar.error(
            title=title,
            content=content,
            orient=Qt.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            duration=2000,
            parent=self
        )

    # @staticmethod
    def one_chart(self, x, y1, y1_name, **kwargs):
        """一个数据图表"""
        c = (
            Line(init_opts=opts.InitOpts(width=f"{kwargs["width"]}px", height=f"{kwargs["height"]}px"))
            .add_xaxis(x)
            .add_yaxis(y1_name, y1, is_smooth=True,
                       markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="min"),
                                                               opts.MarkPointItem(type_="max")
                                                               ]))
            .set_series_opts(
                areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
                label_opts=opts.LabelOpts(is_show=False),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="数据比对图"),
                xaxis_opts=opts.AxisOpts(
                    axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                    is_scale=False,
                    boundary_gap=False,
                ),
                # 鼠标滚动
                datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(is_show=True, type_="inside", is_realtime=True)],
                tooltip_opts=opts.TooltipOpts(is_show=True, trigger="axis", axis_pointer_type="cross"),
            )
            .render("lineChart.html")
        )
        # html = c.render_embed()
        # setattr(Tool, 'html', html)

    def two_chart(self, x, y1, y1_name, y2, y2_name, **kwargs):
        """2个数据图表"""
        c = (
            Line(init_opts=opts.InitOpts(width=f"{kwargs["width"]}px", height=f"{kwargs["height"]}px"))
            .add_xaxis(x)
            .add_yaxis(y1_name, y1, is_smooth=True,
                       markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="min"),
                                                               opts.MarkPointItem(type_="max")
                                                               ]))
            .add_yaxis(y2_name, y2, is_smooth=True,
                       markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="min"),
                                                               opts.MarkPointItem(type_="max")
                                                               ]))
            .set_series_opts(
                areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
                label_opts=opts.LabelOpts(is_show=False),

            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="数据比对图"),
                # pos_left="30%",  # 表示从页面左侧20%的位置开始放置图表
                # pos_top="30%",  # 表示从页面顶部20%的位置开始放置图表
                xaxis_opts=opts.AxisOpts(
                    axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                    is_scale=False,
                    boundary_gap=False,
                ),
                # 鼠标滚动
                datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(is_show=True, type_="inside", is_realtime=True)],
                # 添加这一行为了显示鼠标悬停时的数据
                tooltip_opts=opts.TooltipOpts(is_show=True, trigger="axis", axis_pointer_type="cross"),
                # legend_opts=opts.LegendOpts(pos_left="50%", pos_top="50%")
            )
            .render("lineChart.html")
        )
        # html = c.render_embed()
        # setattr(Tool, 'html', html)
